package com.tyk.bookstore.back.task.schedule;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * @author tyk
 * @description 自定义定时任务执行组件
 */
@Configuration
public class ISchedulingConfigurer implements SchedulingConfigurer {

    @Value("${mine.schedule.thread-pool.size}")
    private int poolSize;

    @Value("${mine.schedule.thread-pool.await-termination}")
    private int awaitTermination;

    @Value("${mine.schedule.thread-pool.name-prefix}")
    private String namePrefix;

    /**
     * 任务注册器
     */
    private ScheduledTaskRegistrar taskRegistrar;

    /**
     * 任务集合
     */
    private final Map<String, ScheduledFuture<?>> taskMap = new HashMap<>();


    @PostConstruct
    private void init() {
        this.taskRegistrar = new ScheduledTaskRegistrar();
        configureTasks(this.taskRegistrar);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        this.taskRegistrar = taskRegistrar;

        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(poolSize);
        taskScheduler.setThreadNamePrefix(namePrefix);
        taskScheduler.setAwaitTerminationSeconds(awaitTermination);
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.initialize();

        taskRegistrar.setTaskScheduler(taskScheduler);
    }

    /**
     * 添加任务
     *
     * @param id   ID
     * @param task 任务
     * @param cron cron表达式
     */
    public void addTask(String id, Runnable task, String cron) {
        ScheduledFuture<?> schedule = taskRegistrar.getScheduler().schedule(
                task,
                new CronTrigger(cron)
        );
        taskMap.put(id, schedule);
    }

    /**
     * 移除任务
     *
     * @param id ID
     */
    public void removeTask(String id) {
        ScheduledFuture<?> scheduledFuture = taskMap.get(id);
        if (scheduledFuture != null) {
            scheduledFuture.cancel(false);
            taskMap.remove(id);
        }
    }

    /**
     * 更新任务
     *
     * @param id   ID
     * @param task 任务
     * @param cron cron表达式
     */
    public void updateTask(String id, Runnable task, String cron) {
        removeTask(id);
        addTask(id, task, cron);
    }


}
